<?php 
class MeasureModel extends Model
{
		 
	
	/**
	 * 添加邮件订阅
	 * @param array $post POST列表
	 */
	public static function insert_email_subscriptions($post)
	{
		
		$data = array(
			'email' => $post['email'],
            'time' => time(),
		);
		$email_registry = D('email_registry');
		$esid = $email_registry->add($data);
		return $esid;
	}
	
	/**
	 * 查询该邮件是否已订阅
	 * @param int $email email
	 */
	public static function email_subscriptions_info($email, $status=1)
	{
		$email_registry = D('email_registry');
		$email_registry->where('email="'.$email.'" and status='.$status);
		$subscriptionInfo = $email_registry->find();

		return $subscriptionInfo;
	}

	/**
	 * 修改邮件订阅状态
	 * @param int $email email
	 */
	public static function email_subscribe_status($email, $status=1)
	{
		$where = array(
			'email' => $email,
		);
		$data = array(
            'status' => $status,
		);
		$email_registry = D('email_registry');
		$esid = $email_registry->where($where)->save($data);
		return $esid;
	}
	/**
	 * 给订阅用户发一次性9折优惠码
	 * @param int $email email
	 */
	public static function email_subscribe_favorable($email)
	{
		global $language_id;
	    $nowtime = time();
	    $favorable['coupon_code'] = 'subs'.substr(uniqid(), -6);
	    $favorable['coupon_money'] = 90;
	    $favorable['max_amount'] = 1000000;
	    $favorable['min_amount'] = 5;  //基本没有使用限制
	    $favorable['start_time'] =  $nowtime;//优惠卷开始使用时间
	    $favorable['expiration_time'] = ($nowtime + 3600*24*30); //结束时间30天
	    $favorable['status'] = 4;//折扣优惠码
	    $favorable['usage_count'] = 1;
	    $favorable['count'] = 1;
	    $favorable['type'] = 4;
	    $favorableRes = M('favorable')->add($favorable);
	    if($favorableRes){
	        $mailInstance = new EmailModel();
	        $email_template = UserModel::get_email_template_info('registryEmail', $language_id);
	        if($email_template){
	            $title    = $email_template['title'];
                //取消订阅地址
	            $unsubscribe_url = self::unsubscribe_url($email);
	            $contentOr = array(
	                '{$coupon}', //优惠码
	                '{$deadline}', //使用截止时间
	                '{$unsubscribe_url}',
	                );
	            $contentRe = array(
	                $favorable['coupon_code'],
	                date('M.jS,Y',$favorable['expiration_time']),
	                $unsubscribe_url,
	                );
	            $contents = str_replace($contentOr,$contentRe,$email_template['content']);
	            $mailInstance->sendMail($email, $title, $contents); 	            
	        }
	    }
    }
	/**
	 * 取消订阅地址
	 * @return string 
	 */     
    public static function unsubscribe_url($email){
        //拼接取消订阅地址
        $email_base64 = base64_encode($email);
        $sign  = MD5($email.C('pwd_key'));
        return $unsubscribe_url = url('measure/unsubscribe','email='.$email_base64.'&sign='.$sign);    	
    }                
	/**
	 * 加入订阅
	 * @return boolean 
	 */   
    public static function add_subscriptions_info($email){
		$subscriptions_info = MeasureModel::email_subscriptions_info($email, 1);
		if(!$subscriptions_info){
			if(self::email_subscriptions_info($email, 0)){
                self::email_subscribe_status($email, 1);
                return true;
			}else{
			    $subscriptionsId = self::insert_email_subscriptions(array('email'=>$email));
		        if($subscriptionsId){
			        //给订阅用户发一次性9折优惠码
			        //20120512取消
                    //self::email_subscribe_favorable($email);
                }
                return true;
		    }
		}
		return false; 
    }

	/**
	 * 查询身型数据的字段
	 * @return array 
	 */
	public static function user_measure_field()
	{
		$user_measure_field_db = D('user_measure_field');
		$user_measure_field = $user_measure_field_db -> select();
		return $user_measure_field;
	}
   /*
    * $measure_mode  量体模式 manual：量尺量体； estimation:免量体
    */
    public function add_measure_data($post,$measure_mode = 'manual'){
        global $user;
            $measure_data = $post['measure'];
			$measure_data2 = $post['measure_data2'];
			$size_measure = $post['size_measure'];
            if($measure_mode == 'manual'){
                $m_status = 1;
            }else if($measure_mode == 'estimation'){
                $m_status = 2;
            }
            if($post['unit']){
                if($post['unit'] == 'ft_in' || $post['unit'] == 'lbs'){
                    $m_unit = 2;
                }else if($post['unit'] == 'cm' || $post['unit'] == 'kgs'){
                    $m_unit = 1;
                }
            }
			foreach($measure_data as $measure_value => $row){
				if($measure_data2[$measure_value]){
					if($measure_data2[$measure_value] == 1){
						if($row['type']){
							$measure2[$measure_value]['cm'] = $row['cm'];
							$measure2[$measure_value]['type'] = $row['type'];
						}else{
							$measure2[$measure_value]['cm'] = $row['cm'];
						}
					}elseif($measure_data2[$measure_value] == 2){
						if($row['type']){
							$measure2[$measure_value]['ft'] = $row['cm'];
							$measure2[$measure_value]['type'] = $row['type'];
						}else{
							$measure2[$measure_value]['ft'] = $row['cm'];
						}
					}elseif($measure_data2[$measure_value] == 3){
						if($row['type']){
							$measure2[$measure_value]['in'] = $row['cm'];
							$measure2[$measure_value]['type'] = $row['type'];
						}else{
							$measure2[$measure_value]['in'] = $row['cm'];
						}
					}
				}else{
					if($measure_data['height']){
						if($measure_data2['shirt']==1){
							$measure2['height']['cm'] = $measure_data['height']['cm'];
						}elseif($measure_data2['shirt']==2){
							$measure2['height']['ft'] = $measure_data['height']['ft'];
						}elseif($measure_data2['shirt']==3){
							$measure2['height']['in'] = $measure_data['height']['in'];
						}
					}
					
					if($measure_data['weight']){
						$measure2['weight']['lb'] = $measure_data['weight']['lb'];
						$measure2['weight']['kg'] = $measure_data['weight']['kg'];
					}
					
					if($measure_data['posture']){
						$measure2['posture']['type'] = $measure_data['posture'];
					}
					
					
				}
			}

			//if($post['is_save']){
				$data = array(
					'user_id' => isset($user['id']) ? intval($user['id']) : 0,
					'sid' => $user['sid'],
					'measure_name' => trim($post['measure_name']),
                    'gendername' => isset($post['gendername']) ? trim($post['gendername']) :"男",
					'measure_data' => is_array($measure_data) ? serialize($measure_data) : '',
					'measure_data2' => is_array($measure2) ? serialize($measure2) : '',
					'size_measure' => is_array($size_measure) ? serialize($size_measure) : '',
					'update_time' => time(),
                    'm_status'=> $m_status,
                  //  'm_unit'=> $m_unit ? $m_unit : 2,
                    'm_unit'=>1,
                    'address_id'=> intval($post['address_id']),
				);
                
                if($post['front_img']){
                	$data['front_img'] = $post['front_img'];
                }
                if($post['side_img']){
                	$data['side_img'] = $post['side_img'];
                }
                //获取身型字段
                $measure_field = self::user_measure_field();

                foreach($measure_field as $value){
                	$field_val = '';
                	if($value['measure_field'] == 'shoulder' || $value['measure_field'] == 'posture'){
                		$field_val = $measure_data[$value['measure_field']]['type'];
                	}else if($value['measure_field'] == 'chest_type'){
                        $field_val = $measure_data['chest']['type'];
                	}else if($value['measure_field'] == 'stomach_type'){
                        $field_val = $measure_data['stomach']['type'];
                	}else{
                		if(empty($value['field_type'])){ 
                            $field_val = $measure_data[$value['measure_field']];
                		}else{ 
                			$field_val = $measure_data[$value['measure_field']][$value['field_type']];
                		}
                	}
                    if($field_val)
                    $data[$value['measure_field']] = $field_val;
                }
                
                if($post['sleeve_size'] && $post['pants_hip']){
                    $data['clothes_size'] = $post['sleeve_size'];//上衣尺码
                    $data['pants_size'] = $post['pants_hip'];//裤子尺码
                }
                $mid = M('user_measure')->add($data);
                return $mid;
    }
   /*
    * $measure_mode = manual：修改量体尺寸； estimation:修改体型
    */
    public static function edit_measure_data($post,$mid,$measure_mode = 'manual'){
              global $user;
           // var_dump($cookie_measure);die;
			$measure_data = $post['measure'];
			$measure_data2 = $post['measure_data2'];
            $size_measure = $post['size_measure'];
			$m_unit = 1;
            if($post['unit']){
                if($post['unit'] == 'ft_in' || $post['unit'] == 'lbs'){
                    $m_unit = 2;
                }else if($post['unit'] == 'cm' || $post['unit'] == 'kgs'){
                    $m_unit = 1;
                }
            }
			$measure2 = array();
			foreach($measure_data as $measure_value => $row){
				if($measure_data2[$measure_value]){
					if($measure_data2[$measure_value] == 1){
						if($row['type']){
							$measure2[$measure_value]['cm'] = $row['cm'];
							$measure2[$measure_value]['type'] = $row['type'];
						}else{
							$measure2[$measure_value]['cm'] = $row['cm'];
						}
					}elseif($measure_data2[$measure_value] == 2){
						if($row['type']){
							$measure2[$measure_value]['ft'] = $row['cm'];
							$measure2[$measure_value]['type'] = $row['type'];
						}else{
							$measure2[$measure_value]['ft'] = $row['cm'];
						}
					}elseif($measure_data2[$measure_value] == 3){
						if($row['type']){
							$measure2[$measure_value]['in'] = $row['cm'];
							$measure2[$measure_value]['type'] = $row['type'];
						}else{
							$measure2[$measure_value]['in'] = $row['cm'];
						}
					}
				}else{
					if($measure_data['height']){
						if($measure_data2['shirt']==1){
							$measure2['height']['cm'] = $measure_data['height']['cm'];
						}elseif($measure_data2['shirt']==2){
							$measure2['height']['ft'] = $measure_data['height']['ft'];
						}elseif($measure_data2['shirt']==3){
							$measure2['height']['in'] = $measure_data['height']['in'];
						}
					}
					
					if($measure_data['weight']){
						$measure2['weight']['lb'] = $measure_data['weight']['lb'];
						$measure2['weight']['kg'] = $measure_data['weight']['kg'];
					}
					
					if($measure_data['posture']){
						$measure2['posture']['type'] = $measure_data['posture'];
					}
					
					
				}
			}
            $measureInfo = M('user_measure')->find($mid);
            if($measureInfo['user_id'] != $user['id']){
                return false;
            }
          
			//if($post['is_save']){
				$data = array(
					'user_id' => isset($user['id']) ? intval($user['id']) : 0,
					'sid' => $user['sid'],
					'measure_name' => $post['measure_name'] ? trim($post['measure_name']) : $measureInfo['measure_name'],
					'measure_data' => is_array($measure_data) ? serialize($measure_data) : '',
					'measure_data2' => is_array($measure2) ? serialize($measure2) : '',
                    'size_measure' => is_array($size_measure) ? serialize($size_measure) : '',
					'update_time' => time(),
                    'm_status'=> $measureInfo['m_status'],
                    'm_unit' => $m_unit ? $m_unit : 2,
				);

                //获取身型字段
                $measure_field = self::user_measure_field();
                if($measure_mode == 'estimation'){
                    $data = array();
                }
                foreach($measure_field as $value){
                    $field_val = '';
                    if($value['measure_field'] == 'shoulder' || $value['measure_field'] == 'posture'){
                        $field_val = $measure_data[$value['measure_field']]['type'];
                    }else if($value['measure_field'] == 'chest_type'){
                        $field_val = $measure_data['chest']['type'];
                    }else if($value['measure_field'] == 'stomach_type'){
                        $field_val = $measure_data['stomach']['type'];
                    }else{
                        if($measure_mode !=  'estimation'){
                            if(empty($value['field_type'])){ 
                                $field_val = $measure_data[$value['measure_field']];
                            }else{ 
                                $field_val = $measure_data[$value['measure_field']][$value['field_type']];
                            }
                        }
                    }
                    if($field_val)
                    $data[$value['measure_field']] = $field_val;
                }
                if($post['sleeve_size'] && $post['pants_hip']){
                    $data['clothes_size'] = $post['sleeve_size'];//上衣尺码
                    $data['pants_size'] = $post['pants_hip'];//裤子尺码
                }

				//修改时保持修改过的数据
				$measureInfo = M('user_measure')->find($mid);
				$edit_data = array();
				foreach($measure_field as $value){
					if( $measureInfo[$value['measure_field']] != $data[$value['measure_field']] ){
				    	if( $value['measure_field'] == 'shoulder' || $value['measure_field'] == 'posture' ||
				           $value['measure_field'] == 'chest_type' || $value['measure_field'] == 'stomach_type' ){
				    		$edit_data[$value['measure_field']] = $measureInfo[$value['measure_field']];
				    	}else if($measure_mode == 'manual'){//只有在修改身形尺寸的时候更新
				    		 $num = $data[$value['measure_field']] - $measureInfo[$value['measure_field']];
				    		 $edit_data[$value['measure_field']] = strval(round($num, 2));
				    	}
					}
				} 
				if($edit_data){
					$edit_measure['measure_id'] = $mid;
					$edit_measure['data'] = serialize($edit_data);
					$edit_measure['edit_time'] = time();
					$edit_measure['type'] = 0;
					D('size_edit_measure')->add($edit_measure);
				}
				if($measure_mode == 'manual'){
				    if($measureInfo['m_status'] == 3){//先有视频量体的客户点添加量体数据 修改身形状态
				        $data['m_status'] = 4;
				    }else if($measureInfo['m_status'] == 2){
				        $data['m_status'] = 1;
				    }
				}
				//修改图片
                if($post['front_img']){
                	$data['front_img'] = $post['front_img'];
                }
                if($post['side_img']){
                	$data['side_img'] = $post['side_img'];
                }
				M('user_measure')->where('id='.$mid)->save($data);
                     

		}

	/**
	 * 保存用户身型照片
     * @param string $img base64格式的图片
     * @param string $subDir 路径
     * @return string 图片路径
	 */
	public static function file_put_images($img, $subDir = '')
	{
		$img=base64_decode($img);
		if(!$subDir) $subDir = date('Y/m/d', time());
		$Path = UPLOAD_PATH.$subDir;
		$mkPath = '.'.$Path;
		if(!is_dir($mkPath)) {
		    mkdir($mkPath,0777,true);
		}
		$filename = uniqid().'.jpg';
		file_put_contents($mkPath.'/'.$filename, $img);
        return $Path.'/'.$filename;
    }
 
	/**
	 * 查询身型数据
	 * @return array 
	 */
	public static function get_measure_one($post)
	{
		$filter = array(
			'user_id' => isset($post['user_id']) ? intval($post['user_id']) : null,
            'address_id' => isset($post['address_id']) ? intval($post['address_id']) : null,
            'id' => isset($post['id']) ? intval($post['id']) : null,
		);

		foreach ($filter as $key => $val){
			if(is_null($val)){
				unset($filter[$key]);
			}
		}

		$user_measure_db = D('user_measure');
		$measure = $user_measure_db->where($filter)->find();
		return $measure;
	}

   /*
    * 选尺码购物 保存尺码
    */
    public function add_msizedata($post,$mid=0){
        global $user;
        $addData = array(       	
            'measure_name' => '选尺码购物',
            'measure_data' => serialize($post),
            'm_status' => '5',
            'update_time' => time(),
        	);
        if($mid > 0){
        	M('user_measure')->where(array('id'=>$mid))->save($addData);
        	$last_id = $post['mid'];            
        }else{
        	$last_id = M('user_measure')->add($addData);
        }
        return $last_id;    
    }
   
    /*
    * 选尺码购物 保存尺码
    */
    public function msizedataShow($sizeType){

        switch ($sizeType) {
        	case '1':
        		return L('Jacket_Size');
        	case '3':
    		    return L('Pant_Size');
        	case '2':
    		    return L('Vest_Size');
           	case '4':
    		    return L('Shirt_Size');
           	case '5':
    		    return L('Coat_Size'); 		 		    		
        }        
    }  
}